package com.hl.ruoyilkshop.service.impl;

import java.nio.charset.StandardCharsets;
import java.text.Collator;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hl.ruoyilkshop.mapper.SkuMapper;
import com.hl.ruoyilkshop.domain.Sku;
import com.hl.ruoyilkshop.service.ISkuService;
import org.springframework.util.DigestUtils;

/**
 * SKUService业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-08
 */
@Service
public class SkuServiceImpl implements ISkuService 
{
    @Autowired
    private SkuMapper skuMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    private static class SpecPair {
        public String name;
        public String value;
    }

    private String normalize(String s) {
        if (s == null) return "";
        return s.trim().replace('\u3000', ' ');
    }

    private String buildSpecKey(List<SpecPair> pairs) {
        Comparator<SpecPair> cmp = Comparator.comparing(
            p -> normalize(p.name), Collator.getInstance(Locale.CHINA)
        );
        return pairs.stream()
            .filter(p -> !normalize(p.name).isEmpty() && !normalize(p.value).isEmpty())
            .sorted(cmp)
            .map(p -> normalize(p.name) + "=" + normalize(p.value))
            .collect(Collectors.joining(";"));
    }

    private String md5(String s) {
        return DigestUtils.md5DigestAsHex(s.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 查询SKU
     * 
     * @param skuId SKU主键
     * @return SKU
     */
    @Override
    public Sku selectSkuBySkuId(Integer skuId)
    {
        return skuMapper.selectSkuBySkuId(skuId);
    }

    /**
     * 查询SKU列表
     * 
     * @param sku SKU
     * @return SKU
     */
    @Override
    public List<Sku> selectSkuList(Sku sku)
    {
        return skuMapper.selectSkuList(sku);
    }

    /**
     * 新增SKU
     * 
     * @param sku SKU
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSku(Sku sku)
    {
        try {
            // 从 spec(JSON) 生成 specKey 和 specKeyHash
            List<SpecPair> pairs = objectMapper.readValue(sku.getSpec(), new TypeReference<List<SpecPair>>(){});
            String specKey = buildSpecKey(pairs);
            String specKeyHash = md5(specKey);
            sku.setSpecKey(specKey);
            sku.setSpecKeyHash(specKeyHash);
        } catch (Exception e) {
            // 如果 spec 为空或解析失败，按无规格处理
            String specKey = "__NOSPEC__";
            String specKeyHash = md5(specKey);
            sku.setSpecKey(specKey);
            sku.setSpecKeyHash(specKeyHash);
        }
        // 幂等保存：唯一键冲突则更新价格/库存/货号/图片
        return skuMapper.upsertSku(sku);
    }

    /**
     * 修改SKU
     * 
     * @param sku SKU
     * @return 结果
     */
    @Override
    public int updateSku(Sku sku)
    {
        return skuMapper.updateSku(sku);
    }

    /**
     * 批量删除SKU
     * 
     * @param skuIds 需要删除的SKU主键
     * @return 结果
     */
    @Override
    public int deleteSkuBySkuIds(Integer[] skuIds)
    {
        return skuMapper.deleteSkuBySkuIds(skuIds);
    }

    /**
     * 删除SKU信息
     * 
     * @param skuId SKU主键
     * @return 结果
     */
    @Override
    public int deleteSkuBySkuId(Integer skuId)
    {
        return skuMapper.deleteSkuBySkuId(skuId);
    }
}
